Skip to main content

IndexError list index out of range error principle and solution -python

· 3 Minutes to read
Allen Ma

Problems identified

When I was writing the article Financial Data Analysis (I) python previewThe following error was reported for Project 2: Calculating the annual growth rate of mobile phone sales.在这里插入图片描述 It looks like the results have been run, but the long string in front of it is really uncomfortable to watch. This, coupled with the fact that ==Process finished with exit code 1== makes me even more convinced that there is something fishy going on here.

As shown in the diagram, the error message is

Traceback (most recent call last):
IndexError: list index out of range

Find out why

After searching for information on the subject I learned that there are two main reasons why list index out of range errors occur.

One possibility is that the subscript is out of range. one could be that the list is empty, without a single element

Let me next illustrate this abstraction with an example. Open idle and enter the following code

>>> li = [1,2,3,4,5,6,7,8,9,10]
>>> #Index[0,1,2,3,4,5,6,7,8,9 ]
>>> li[8]
9
>>> li[10]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
li[10]
IndexError: list index out of range
>>> # Like this, the index value is out of the loop, also called out of bounds

Trying to solve

First attempt to solve. Add the try... .except module

for s in linestr:
try:
L = s.split('\t')
print(L[0], end=" ")
print(isBigGrowth(L, 0.3))
except:
print('运行失败')

Results of the run: 在这里插入图片描述As you can see, the headache-inducing red error message is gone, and ==Process finished with exit code 0== The problem seems to have been solved, but we know that this is only superficial and that the problem has not been solved, but we have chosen not to display it. The cure is not the cause!

Second attempt to resolve. I noticed that the program was throwing an exception at the last entry. The mobile company is able to analyse and determine all of them, so could it be the second cause of the error? There was the empty list. So I checked the source documentation and found that there was indeed an empty line at the end. 在这里插入图片描述 After removing the blank line at the end, run the program again: 在这里插入图片描述 Now that's perfect! Comfortable =。=

Summary

It is very important to check the format of the data being analysed before processing it!